<script setup>
import { useRequest, useWatch, useDownload } from '@/hooks';
import { useSelectIns } from '@/store/zdwh.js';
import { useTitleChange } from '../hooks.js';
import { getDeviceSysTree, getDSNodeInfo, delDeviceSys } from '@/api/index.js';
import { Message, MessageBox } from 'element-ui';
import ToolTip from '@/components/ToolTip/index.vue';
import DialogDeviceSys from './DialogDeviceSys.vue';
import DialogDSImport from './DialogDSImport.vue';

const selectInsStore = useSelectIns();
const dsTree = ref(null);
const [dsTitle, setDSTitle] = useTitleChange();
const dialogDeviceSys = ref(null);
const dialogDSImport = ref(null);
const editData = ref(null);
const defaultProps = { children: 'children', label: 'name' };
const superiorName = ref('-');
const nodeInfoList = [
  { name: '设备系统ID', key: 'dsViewId' },
  { name: '设备系统名称', key: 'dsName' },
  { name: '同级排序号', key: 'sortNum' },
];

const addTopNode = () => {
  setDSTitle('新增');
  dialogDeviceSys.value.visible = true;
};
const handleImport = () => {
  dialogDSImport.value.visible = true;
};
const handleDownload = () => {
  useDownload('/energyservice/device/system/templateDownload', {}, '设备系统树模板.xlsx');
};
const addChildNode = (node, data) => {
  setDSTitle('新增');
  dialogDeviceSys.value.visible = true;
  dialogDeviceSys.value.formData.superDsCode = data.id;
};
const editNode = (node, data) => {
  setDSTitle('编辑');
  dialogDeviceSys.value.visible = true;
};
const delNode = (node, data) => {
  MessageBox.confirm('删除后不可找回，是否确认删除', '提示', {
    confirmButtonText: '是',
    cancelButtonText: '否',
    type: 'warning',
  }).then(() => {
    runDel({ dsCode: data.id });
  });
};

const handleNodeClick = (data, node) => {
  runNodeInfo({ dsCode: data.id });
  superiorName.value = node.parent.data?.name ?? '-';
  dialogDeviceSys.value.superiorName = superiorName.value;
};
const handleSuccess = bool => {
  if (bool) {
    runTree(treeParams.value);
  }
};
const treeParams = ref({ enterpriseCode: selectInsStore.selectIns?.enterpriseCode });
const [dsTreeData, loading, runTree] = useRequest(getDeviceSysTree, {
  manual: true,
  onSuccess: res => {
    if (res.code === 200) {
      superiorName.value = '-';
      if (res.data?.length > 0) {
        runNodeInfo({ dsCode: res.data[0].id });
        nextTick(() => {
          dsTree.value.setCurrentKey(dsTreeData.value[0]?.id);
        });
      } else {
        nodeData.value = null;
      }
    }
  },
});
const [nodeData, nLoading, runNodeInfo] = useRequest(getDSNodeInfo, {
  manual: true,
  onSuccess: res => {
    if (res.code === 200) {
      if (dsTitle.value === '编辑') editData.value = res.data;
    }
  },
});
const [, , runDel] = useRequest(delDeviceSys, {
  manual: true,
  onSuccess: res => {
    if (res.code === 200) {
      Message.success(res.msg);
      runTree(treeParams.value);
    }
  },
});
useWatch(
  () => selectInsStore.selectIns,
  n => {
    if (n?.enterpriseCode) {
      treeParams.value.enterpriseCode = n.enterpriseCode;
      runTree(treeParams.value);
    }
  },
  { deep: true, immediate: true },
);
</script>

<template>
  <ul class="u-w100 u-h100 u-df-spb DeviceSystTree-wrapper">
    <li class="u-p20 u-mr20 u-base-fg">
      <div class="u-prim-text u-fs20">设备系统树</div>
      <div class="u-mt20 u-mb20">
        <el-button type="primary" size="small" plain @click="addTopNode">添加顶级节点</el-button>
        <el-button type="primary" size="small" plain @click="handleImport">导入设备系统</el-button>
        <el-button type="primary" size="small" plain @click="handleDownload">下载模板</el-button>
      </div>
      <el-tree
        ref="dsTree"
        v-loading="loading"
        :data="dsTreeData ?? []"
        :props="defaultProps"
        :highlight-current="true"
        :current-node-key="dsTreeData?.[0]?.id ?? null"
        :expand-on-click-node="false"
        node-key="id"
        default-expand-all
        style="height: calc(100% - 98px); overflow-y: auto"
        @node-click="handleNodeClick"
      >
        <span class="custom-tree-node u-fs14" slot-scope="{ node, data }">
          <ToolTip class="tree-lable u-pr20" :content="data.name" effect="dark" />
          <span class="u-sec-text">
            <i class="toolBtn el-icon-plus u-mr5" @click="addChildNode(node, data)"></i>
            <i class="toolBtn el-icon-edit-outline u-mr5" @click="editNode(node, data)"></i>
            <i v-show="node.isLeaf" class="toolBtn el-icon-delete" @click="delNode(node, data)"></i>
          </span>
        </span>
      </el-tree>
    </li>
    <li class="u-p20 u-base-fg">
      <div class="u-prim-text u-fs20">设备系统详情</div>
      <ul v-loading="nLoading" class="u-mt20">
        <li class="u-df-spb">
          <span class="u-prim-text">上级设备系统名称</span>
          <span class="u-reg-text">{{ superiorName }}</span>
        </li>
        <li v-for="item in nodeInfoList" :key="item.key" class="u-df-spb u-mt20">
          <span class="u-prim-text">{{ item.name }}</span>
          <span class="u-reg-text">{{ nodeData?.[item.key] ?? '-' }}</span>
        </li>
      </ul>
    </li>
    <DialogDeviceSys ref="dialogDeviceSys" :dsTitle="dsTitle" :editData="editData" @success="handleSuccess" />
    <DialogDSImport ref="dialogDSImport" @success="handleSuccess" />
  </ul>
</template>

<style lang="scss" scoped>
.DeviceSystTree-wrapper {
  > li {
    flex: 1;
    height: 100%;
    overflow-y: auto;
  }
}
</style>
